<template>
  <div class="page-header-index-wide">
    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <a-select style="width: 140px" v-model="newUser.timeSlot" @change="timeSlotChange">
                <a-select-option value="week">最近七天</a-select-option >
                <a-select-option value="month">最近三十日</a-select-option >
                <a-select-option value="quarter">最近三个月</a-select-option >
                <a-select-option value="custom">自定义</a-select-option >
              </a-select>
            </div>
            <a-range-picker :style="{width: '256px'}"
                            @change="dateChange"
                            v-model="newUser.date"
                            format="YYYY-MM-DD"
                            :disabledDate="disabledDate"
            />
          </div>
          <a-tab-pane :fields="visitFields" loading="true" tab="新增IP数" key="1">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="新增IP数" :dataSource="barData" yaxisText="新增IP数"/>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="新增IP数日排行" :list="rankList"/>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>

    <a-row>
<!--      <a-col :span="24">-->
<!--        <a-card :loading="loading" :bordered="false" title="最近一周访问次数统计" :style="{ marginTop: '24px' }">-->
<!--          <a-row>-->
<!--            <a-col :span="6">-->
<!--              <head-info title="今日访问IP数" :content="loginfo.todayIp"></head-info>-->
<!--            </a-col>-->
<!--            <a-col :span="2">-->
<!--              <a-spin class='circle-cust'>-->
<!--                <a-icon slot="indicator" type="environment" style="font-size: 24px"  />-->
<!--              </a-spin>-->
<!--            </a-col>-->
<!--            <a-col :span="6">-->
<!--              <head-info title="今日访问次数" :content="loginfo.todayVisitCount"></head-info>-->
<!--            </a-col>-->
<!--            <a-col :span="2">-->
<!--              <a-spin class='circle-cust'>-->
<!--                <a-icon slot="indicator" type="team" style="font-size: 24px"  />-->
<!--              </a-spin>-->
<!--            </a-col>-->
<!--            <a-col :span="6">-->
<!--              <head-info title="访问总次数" :content="loginfo.totalVisitCount"></head-info>-->
<!--            </a-col>-->
<!--            <a-col :span="2">-->
<!--              <a-spin class='circle-cust'>-->
<!--                <a-icon slot="indicator" type="rise" style="font-size: 24px"  />-->
<!--              </a-spin>-->
<!--            </a-col>-->
<!--          </a-row>-->
<!--          <line-chart-multid :fields="visitFields" :dataSource="visitInfo"></line-chart-multid>-->
<!--        </a-card>-->
<!--      </a-col>-->
    </a-row>
  </div>
</template>

<script>
  import ChartCard from '@/components/ChartCard'
  import ACol from "ant-design-vue/es/grid/Col"
  import ATooltip from "ant-design-vue/es/tooltip/Tooltip"
  import MiniArea from '@/components/chart/MiniArea'
  import MiniBar from '@/components/chart/MiniBar'
  import MiniProgress from '@/components/chart/MiniProgress'
  import RankList from '@/components/chart/RankList'
  import Bar from '@/components/chart/Bar'
  import LineChartMultid from '@/components/chart/LineChartMultid'
  import HeadInfo from '@/components/tools/HeadInfo.vue'
  import moment from 'moment';

  import Trend from '@/components/Trend'
  import { getLoginfo,getVisitInfo } from '@/api/api'

  let that;


  /**数组根据数组对象中的某个属性值进行排序的方法
   * 使用例子：newArray.sort(sortBy('number',false)) //表示根据number属性降序排列;若第二个参数不传递，默认表示升序排序
   * @param attr 排序的属性 如number属性
   * @param rev true表示升序排列，false降序排序
   * */
  function sortBy(attr,rev){
    //第二个参数没有传递 默认升序排列
    if(rev ==  undefined){
      rev = 1;
    }else{
      rev = (rev) ? 1 : -1;
    }
    return function(a,b){
      a = a[attr];
      b = b[attr];
      if(a < b){
        return rev * -1;
      }
      if(a > b){
        return rev * 1;
      }
      return 0;
    }
  }

  export default {
    name: "UserChart",
    components: {
      ATooltip,
      ACol,
      ChartCard,
      MiniArea,
      MiniBar,
      MiniProgress,
      RankList,
      Bar,
      Trend,
      LineChartMultid,
      HeadInfo
    },
    data() {
      return {
        loading: true,
        center: null,
        rankList:[],
        barData:[],
        loginfo:{},
        visitFields:['ip','visit'],
        visitInfo:[],
        newUser:{
          timeSlot:"week",
          date:[]
        },
        indicator: <a-icon type="loading" style="font-size: 24px" spin />,

      }
    },
    created() {
      that = this;
      this.initLogInfo();
      this.initParam();
    },
    methods: {
      initLogInfo () {
        getLoginfo(null).then((res)=>{
          if(res.success){
            Object.keys(res.result).forEach(key=>{
              res.result[key] =res.result[key]+""
            })
            this.loginfo = res.result;
          }
        })
        getVisitInfo().then(res=>{
          if(res.success){
             this.visitInfo = res.result;
           }
         })
      },

      /**
       * 初始化相关参数
       */
      initParam(){

        //初始化时间设置
        that.setNewUserDate();
      },
      /**
       * 禁止选择的时间段
       */
      disabledDate(current) {
        return current < moment(that.$getDate({date:new Date(2020,0,0)})).endOf('day') || current > moment().endOf('day')
      },
      setNewUserDate(key){
        let times = 3600*24*1000*7;
        switch (key) {
          case "week":times = 3600*24*1000*7;
            break;
          case "month":times = 3600*24*1000*30;
            break;
          case "quarter":times = 3600*24*1000*90;
            break;
          case "custom":return false;
            break;
          default:times = 3600*24*1000*7;
            break;
        }
        let data = that.$getDate({});
        let data1 = that.$getDate({date : new Date(new Date().getTime() - times)})
        that.newUser.date = [moment(data1),moment(data)];
        that.getNewUser();
      },

      /**
       * 新增用户数的时间段改变
       */
      timeSlotChange(e){
        that.setNewUserDate(e);
      },
      dateChange(e){
        that.newUser.timeSlot = "custom";
        that.getNewUser();
      },
      getNewUser(){
        that.loading = true;
        let start = moment(that.newUser.date[0]).format("YYYY-MM-DD");
        let end = moment(that.newUser.date[1]).format("YYYY-MM-DD");
        that.$Request({
          url:"/statistics/recentDayAddUsers",
          params:{
            start:start,
            end:end
          }
        }).then(res=>{
         let rankList =  res.result.sort(sortBy('total',false))
          rankList = JSON.parse(JSON.stringify(rankList).replace(/day/g, 'name'))
          that.rankList = rankList;
          let bar = [];
          let s = new Date(start).getTime();let e = new Date(end).getTime();

          while (e > s) {
            let obj = {x:that.$getDate({date:new Date(s)}),y:0}
            for(let item of res.result){
              if(that.$getDate({date:new Date(s)}) == item.day){
                obj.y = item.total;
                break;
              }
            }
            s += 3600*1000*24;

            bar.push(obj)
          }
          that.barData = bar;
        }).catch(res=>{
          if(!res){
            res = "新增用户数据加载失败"
          }
          that.$message.warning(res)
        }).finally(()=>{
          that.loading = false;
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .circle-cust{
    position: relative;
    top: 28px;
    left: -100%;
  }
  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }

  /* 首页访问量统计 */
  .head-info {
    position: relative;
    text-align: left;
    padding: 0 32px 0 0;
    min-width: 125px;

    &.center {
      text-align: center;
      padding: 0 32px;
    }

    span {
      color: rgba(0, 0, 0, .45);
      display: inline-block;
      font-size: .95rem;
      line-height: 42px;
      margin-bottom: 4px;
    }
    p {
      line-height: 42px;
      margin: 0;
      a {
        font-weight: 600;
        font-size: 1rem;
      }
    }
  }
</style>